package com.example.sxproject.controller;


import com.example.sxproject.pojo.*;
import com.example.sxproject.service.CardService;
import com.example.sxproject.service.PaymentService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private CardService cardService;

    //管理员查看全部账单不加限制
    @PostMapping ("/selectAll")
    public Result SelectAll(){
        //查询用户
        List<Payment> p = paymentService.selectAll();
        return Result.success(p);

    }

    //通过检索流水号查找
    @PostMapping("/selectByNumber")
    public Result selectByIdNumber(String idNumber){
        List<Payment> p = paymentService.selectByIdNumber(idNumber);
        return Result.success(p);
    }

    //多条件检索
    @PostMapping("/selectBySearchstr")
    public Result selectBySearchStr(SearchStr searchStr, HttpSession session){
        List<Payment> p = paymentService.selectBySearchStr(searchStr);
        session.setAttribute("payments", p); //存到session中
        return Result.success(p);
    }

    //日期筛选
    @PostMapping("/selectByDate")
    public String selectByDate(String lowTime, String highTime, HttpSession session){

        List<Payment> res = new ArrayList<>();

        User user = (User) session.getAttribute("user"); //获取session中的信息，并强制转化成User类型
        List<Payment> payments = paymentService.getPaymentsByUserId(user.getId());// 返回全部支付记录

        // 使用默认的 ISO_LOCAL_DATE 格式解析日期字符串 表示一个没有时区的日期
        LocalDate date1 = LocalDate.parse(lowTime, DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate date2 = LocalDate.parse(highTime, DateTimeFormatter.ISO_LOCAL_DATE);


        for(Payment payment : payments) {

            String time = payment.getPayDate().substring(0, 10);
            LocalDate tem = LocalDate.parse(time, DateTimeFormatter.ISO_LOCAL_DATE);

            if(tem.isBefore(date1) || tem.isAfter(date2)) {
                continue;
            }
            res.add(payment);
        }

        session.setAttribute("payments", res); //存到session中
        return "money";
    }

    //添加：添加一个支付记录 + 支付功能
    @RequestMapping("/addPayment")
    public String addPayment(PayMessage payMessage, HttpSession session) {

        //验证银行卡密码
        if (!cardService.verifyPassword(payMessage.getCardId(), payMessage.getPassword())) {
            session.setAttribute("msg", "密码错误");
            return "transferAssure";
        }

        //查找2个卡的信息
        Card card1 = cardService.findByIdNumber(payMessage.getCardId());//根据卡号找记录1:支付卡
        Card card2 = cardService.findByIdNumber(payMessage.getRecardId());//根据卡号找记录2：接收卡

        double money = payMessage.getMoney();//转账金额

        //余额验证
        if(card1.getBalance() < money) {
            session.setAttribute("msg", "余额不足");
            return "transferAssure";
        }

        //更新银行卡余额，实现转钱
        cardService.updateBalance(card1.getIdNumber(), card1.getBalance() - money);// 进行转钱操作
        cardService.updateBalance(card2.getIdNumber(), card2.getBalance() + money);


        //传进来的参数要包括 支付卡号、接收卡号、金额、支付类型
        Payment payment = new Payment();  //第一个交易记录
        Payment payment1 = new Payment(); // 第二个交易记录

        //流水号
        UUID uuid1 = UUID.randomUUID(); // 使用uuid生成随机32位
        UUID uuid2 = UUID.randomUUID();

        payment.setIdNumber(String.valueOf(uuid1));
        payment1.setIdNumber(String.valueOf(uuid2));

        //支付方 和 接收方
        payment.setCardId(payMessage.getCardId()); // 第一个记录的支付方 接收方
        payment.setRecardId(payMessage.getRecardId());
        payment1.setCardId(payment.getRecardId()); // 第二个 交换支付方和接收方
        payment1.setRecardId(payment.getCardId());

        //支付时间，获取当前时间，转为string类型
        String time = LocalDateTime.now().toString();
        time = time.substring(0, 19);
        time = time.replace('T', ' ');
        payment.setPayDate(time);
        payment1.setPayDate(payment.getPayDate());

        //支付金额
        payment.setMoney(payMessage.getMoney());
        payment1.setMoney(payMessage.getMoney());

        // 更改支付类型 1转入 2转出
        payment.setTransType(2);
        payment1.setTransType(1);

        //支付类型 1 转账
        payment.setPayType(1);
        payment1.setPayType(1);

        //更新所属用户
        payment.setUserId(card1.getUserId());
        payment1.setUserId(card2.getUserId());

        //当前记录状态
        payment.setPaymentStatus(1);
        payment1.setPaymentStatus(1);

        paymentService.addPayment(payment);
        paymentService.addPayment(payment1);

        session.setAttribute("msg", "");
        return "success";

    }


    //更新：支付记录假删除
    @PutMapping("/deletepayment")
    public Result deletePayment(@RequestBody @Validated Payment payment) {
        payment.setPaymentStatus(2);
        paymentService.deletePayment(payment);
        return Result.success();
    }

    //查询：通过userId查询支付记录
   @GetMapping("/getPaymentsByUserId")
   public Result getPaymentsByUserId(@RequestParam Integer userId) {
       List<Payment> payments= paymentService.getPaymentsByUserId(userId);
       return Result.success(payments);
   }
}
